import React, {Component} from 'react';
import PropTypes from 'prop-types';

import TabNav from './TabNav';
import TabContent from './TabContent';

class Tabs extends Component {
  static defaultProps = {
    classPrefix: 'tabs',
    onChange: () => {}
  }
  static propTypes = {
    classPrefix: PropTypes.string,
    className: PropTypes.string,
    defaultActiveIndex: PropTypes.number,
    activeIndex: PropTypes.number,
    onChange: PropTypes.func,
    children: PropTypes.oneOfType([
      PropTypes.arrayOf(PropTypes.node),
      PropTypes.node
    ])
  }
  constructor (props) {
    super(props);
    let activeIndex = 0;
    let curProps = this.props;
    if ('activeIndex' in curProps) {
      // 外部更新
      activeIndex = curProps.activeIndex;
    } else if ('defaultActiveIndex' in curProps) {
      activeIndex = curProps.defaultActiveIndex;
    }
    this.state = {
      activeIndex,
      prevIndex: activeIndex
    };
  }
  componentWillReceiveProps (nextProps) {
    if ('activeIndex' in nextProps) {
      this.setState({activeIndex: nextProps.activeIndex});
    }
  }
  handleTabClick (activeIndex) {
    console.log(this.state.activeIndex, activeIndex);
    const prevIndex = this.state.activeIndex;
    if (this.state.activeIndex !== activeIndex && 'defaultActiveIndex' in this.props) {
      this.setState({activeIndex, prevIndex});
      this.props.handleChange({activeIndex, prevIndex});
    }
  }
  // 渲染Nav
  renderTabNav () {
    // console.log(this.props);
    const {classPrefix, activeIndex, children} = this.props;
    // console.log(this.props.activeIndex);
    return (
      <TabNav
        classPrefix={classPrefix}
        activeIndex={this.state.activeIndex}
        panels={children}
        handleChange={this.handleTabClick.bind(this)}
      ></TabNav>
    )
  }
  renderTabContent () {
    const {classPrefix, activeIndex, children} = this.props;
    return (
      <TabContent
        classPrefix={classPrefix}
        activeIndex={this.state.activeIndex}
        panels={children}
      ></TabContent>
    )
  }
  render () {
    return (
      <div>
        <div className="tabs-bar">
          {
            this.renderTabNav()
          }
        </div>
        {
          this.renderTabContent()
        }
      </div>
    )
  }
}

export default Tabs;
